import polyv from '@/lib/polyv.js'
import parseHtml from '@/utils/parseHtml.js'

/**
 * 延时器：用于模拟异步请求
 */
let sleep = function(time) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve()
		}, time)
	})
}


// console.log(dataOrigin);
let dataTest = function(type) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve(dataOrigin[type])
		}, 500)
	})
}

/* 
 *请求
 */
let request = function(url, param = {}, method = 'POST') {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: method || 'POST',
			data: Object.assign({}, param),
			header: Object.assign({
				"BZ": "XCX",
				"TOKEN": "oboPr4vVyUu2hMV_7aFdggLGFiKo",
				'Content-Type': 'application/x-www-form-urlencoded'
			}),
			success: res => {
				uni.hideLoading()
				resolve(res)
			},
			fail: (e) => {
				console.log('请求失败1');
				reject(e)
			},
			complete() {
				// uni.hideLoading()
			}
		});
	})
}

/* 登录 */
let login = function() {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: '',
			success: res => {
				resolve(res)
			},
			fail: e => {
				reject("登录失败" + e)
			}
		});
	})
};

// 提示信息
let toast = function(options) {
	options = Object.assign({
		duration: 2000,
		icon: 'none',
		mask: false,
	}, options)
	if (Boolean(options.title) === false) {
		return;
	}
	uni.showToast(options)
}



// 生成随机验证码
let identifyCode = function() {
	function rand(min, max) {
		return parseInt(min + Math.random() * (max - min + 1))
	}
	return rand(1111, 9999)
}

// 从微信服务器获取 session 相关信息
let code2Session = async function(code) {
	
	//let url =
		//`https://api.weixin.qq.com/sns/jscode2session?appid=${config.appId}&secret=${config.appSecret}&js_code=${code}&grant_type=authorization_code`;
	//return await request(url)
}

/**
 * 保留当前页面跳转到指定页面
 */
let navTo = function(path) {
	uni.navigateTo({
		url: path
	})
}

/**
 * 重定向到指定页面
 */
let redirectTo = function(path) {
	uni.redirectTo({
		url: path
	})
}

/**
 * 跳转到指定tabbar
 */
let swichTab = function(path) {
	uni.switchTab({
		url: path
	})
}

// 检测函数
let check = {
	phone: (phone) => {
		if (!(/^1[3456789]\d{9}$/.test(phone))) {
			return false;
		} else {
			return true;
		}
	}
}

// storage 本地存储
let setStorage = function(key, data) {
	return new Promise((resolve, reject) => {
		uni.setStorage({
			key,
			data,
			success() {
				resolve(true)
			},
			fail(e) {
				reject(`${key}存储失败,${e}`)
			}
		});
	})
}

// 读取本地存储
let getStorage = function(key) {
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key,
			success(res) {
				resolve(res.data)
			},
			fail(e) {
				console.log(`读取 ${key} 失败`);
				reject(e)
			}
		});
	})
}

// 清除本地存储
let rmStorage = function(key) {
	return new Promise((resolve, reject) => {
		uni.removeStorage({
			key,
			success(res) {
				resolve(true)
			},
			fail(e) {
				console.log(`清除 ${key} 失败`);
				reject(e)
			}
		})
	})
}

// 更改navigationBarTitle
let setTitle = function(title) {
	return new Promise((resolve, reject) => {
		uni.setNavigationBarTitle({
			title,
			success() {
				resolve()
			},
			fail(e) {
				reject(`设置导航栏标题失败${e}`)
			}
		})
	})
}

// 将秒数转换为时分秒
let timeFormat = function(time) {
	let h, m, s
	let str = ''
	h = parseInt(time / 3600)
	m = parseInt((time - h * 3600) / 60)
	s = time - h * 3600 - m * 60
	return `${format(h)}:${format(m)}:${format(s)}`

	function format(str) {
		str = str.toString()
		return str.length < 2 ? `0${str}` : str
	}
}

// 格式化从服务端获取到的时间戳 date为时间戳
let timeTrans = function(date, time) {
	if(!date) {
		return
	}
	if (date.includes('-')) {
		return data
	}
	date = new Date(parseInt(date) * 1000)
	// console.log(date);
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	if (time) {
		return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
	} else {
		return [year, month, day].map(formatNumber).join('-')
	}
	// return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')

	function formatNumber(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}
}

// 根据图片地址返回服务器地址 如：/Uploads/2016-08-25/57bebaa741bfc.jpg 返回 www.daoyoupeixun.cn/uploads/...
let picPath = function(path) {
	// console.log(config.baseUrl + path);
	let reg = /(http)|(https)/
	if (reg.test(path)) {
		return path
	}
	return config.baseUrl + path
}


let idToPic = function(id) {
	let url = `https://www.daoyoupeixun.cn/wx.php/app/Pic/id/${id}`
	return new Promise((resolve, reject) => {
		request(url).then(res => {
			resolve(picPath(res.data.url))
		})
	})
}

// 从元数据对象中获取所需的属性 relation是映射关系对象,其键名是元数据的键名，键值是所需对象的键名
let pickAttrInObj = function(obj, relation) {
	let newObj = {}
	for (let key in relation) {
		newObj[relation[key]] = obj[key]
	}
	return newObj
}

// // 拼接路由参数 params是参数对象
// let routerParam = function(params) {
// 	let str = ''
// 	for (let key in params) {
// 		str += `&${key}=${params[key]}`
// 	}
// 	return '?' + str.slice(1)
// }

/*
 * obj 转 params字符串参数
 * 例子：{a:1,b:2} => a=1&b=2
 */
let objParseParam = function(obj) {
	// console.log(obj);
	// return
	let paramStr = ''
	if (obj instanceof Array) return paramStr
	if (!(obj instanceof Object)) return paramStr
	for (let key in obj) {
		paramStr = paramStr + `&${key}=${obj[key]}`
	}
	return paramStr.slice(1)
}

/*
 * obj 转 路由地址带参数
 * path 是地址 obj 是参数对象
 * 例子：{a:1,b:2} => /pages/index/index?a=1&b=2
 */
let objParseUrlAndParam = function(path, obj) {
	let url = path || '/'
	let paramStr = objParseParam(obj)
	paramStr && (url += '?')
	url += paramStr
	return url
}

let showModal = function({
	title = '标题',
	content = '提示内容',
	cancelText = '取消',
	confirmText = '确定',
	success
}) {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title,
			content,
			cancelText,
			confirmText,
			success
		})
	})
}

// 将选项转为大写
let upPer = function(str) {
	if (str) {
		return str.toUpperCase()
	}
}

// 转换正确率
let rightRate = function(rightTimes, errorTimes) {
	if (rightTimes && errorTimes) {
		rightTimes = parseInt(rightTimes)
		errorTimes = parseInt(errorTimes)
		return Math.floor((rightTimes / (rightTimes + errorTimes)) * 100)
	}
	return 0
}

let getVideoInfo = function(vid) {
	return new Promise((resolve, reject) => {
		let vidObj = {
			vid: vid,
			callback: function(videoInfo) {
				resolve(videoInfo)
			},
		};
		polyv.getVideo(vidObj)
	})
}

let model = function(opt) {
	return new Promise((resolve, reject) => {
		uni.showModal({
			...opt,
			success: (res) => {
				resolve(res)
			},
			fail: (e) => {
				reject(e)
			}
		})
	})
}

// 去除题目中的空行
let trim = function(str) {
	if (str) {
		let reg = /\n/g
		return str.replace(reg, '')
	}
}

// 获取服务供应商
let provider = function(service) {
	return new Promise((resolve,reject) => {
		uni.getProvider({
			service,
			success(e) {
				resolve(e.provider)
			},
			fail(e) {
				console.log('获取服务供应商失败');
				reject(e)
			}
		})
	})
}

// 支付
let payment = function(param) {
	return new Promise((resolve,reject) => {
		uni.requestPayment({
			provider:param.provider,
			orderInfo:param.orderInfo,
			timeStamp:param.timeStamp,
			nonceStr:param.nonceStr,
			package:param.package,
			signType:param.signType,
			paySign:param.paySign,
			success(e) {
				// console.log(e);
				resolve(true)
			},
			fail(e) {
				console.log('调用支付接口失败');
				console.log(e);
				reject(false)
			}
		})
	})
}

// 分享给朋友
let onShareAppMessage = function() {
	return {
		title: '雅正导游考试在线题库',
		path: '/pages/index/index'
	};
}

// 分享朋友圈
let onShareTimeline = function() {
	return {
		title:'雅正导游考试在线题库',
		imageUrl:'/static/img/logo.jpg'
	}
}
export default {
	dataTest,
	login,
	request,
	toast,
	identifyCode,
	sleep,
	code2Session,
	navTo,
	redirectTo,
	swichTab,
	check,
	getStorage,
	setStorage,
	rmStorage,
	setTitle,
	timeFormat,
	timeTrans,
	picPath,
	idToPic,
	pickAttrInObj,
	// routerParam,
	objParseParam,
	objParseUrlAndParam,
	showModal,
	upPer,
	rightRate,
	getVideoInfo,
	parseHtml,
	model,
	trim,
	provider,
	payment,
	onShareAppMessage,
	onShareTimeline
}
